package net.vinote.smart.platform.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.vinote.smart.platform.service.bean.AppInfo;
import net.vinote.smart.platform.service.bean.AppItem;
import net.vinote.smart.platform.service.bean.CodeLibrary;
import net.vinote.smart.platform.service.bean.User;
import net.vinote.smart.platform.util.JsonUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MainPageController {
	@RequestMapping("main_page.html")
	public ModelAndView viewContract(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("main_page");

		String subject = request.getParameter("subject");
		User CurUser = (User) (request.getSession().getAttribute("user"));

		JSONArray subjects = new JSONArray();
		List<CodeLibrary> list = CurUser.getSubjectList();
		if (list.size() > 0) {
			if (subject == null) {
				subject = list.get(0).getItemNo();
			}

			for (CodeLibrary lib : list) {
				JSONObject json = new JSONObject();
				json.put("id", lib.getItemNo());
				json.put("text", lib.getItemName());
				if (lib.getItemNo().equals(subject)) {
					json.put("selected", true);
				}
				subjects.put(json);
			}
			mav.addObject("subjects", subjects);
		} else {
			throw new RuntimeException();
		}

		JSONArray appJsonArray = new JSONArray();
		List<AppInfo> appList = CurUser.getAppInfoBySubject(subject);
		for (AppInfo app : appList) {
			List<AppItem> itemList = CurUser.getAppItemByAppID(app.getAppID());
			JSONObject appJson = JsonUtil.getJsonObject(app);
			appJson.put("items", itemList);
			appJsonArray.put(appJson);
		}

		mav.addObject("appJSON", appJsonArray);
		return mav;
	}
}
